import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/alert_business/video/video_buy_alert.dart';
import 'package:xvideos/hj_page/home_business/widget/image_scale_view.dart';
import 'package:xvideos/hj_utils/api_service/vid_service.dart';
import 'package:xvideos/hj_utils/player_util.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';
import 'package:xvideos/tools_base/widget/scroll_positioned_list/src/scrollable_positioned_list.dart';

import '../../../alert_business/video/video_buy_bottom_sheet.dart';
import '../../../hj_model/video_model.dart';
import '../../../tools_base/widget/scroll_positioned_list/src/item_positions_listener.dart';
import 'album_action_widget.dart';

class PicsImagePage extends StatefulWidget {
  final VideoModel? videoModel;
  final int index;
  final bool isFromDetail;

  const PicsImagePage({
    Key? key,
    this.videoModel,
    this.index = 0,
    this.isFromDetail = false,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PicsImagePageState();
  }
}

class _PicsImagePageState extends State<PicsImagePage> {
  VideoModel? videoModel;
  ValueNotifier<int> _indexNotifier = ValueNotifier<int>(0); //局部刷新
  final itemPositionsListener = ItemPositionsListener.create();
  final itemScrollCtr = ItemScrollController();

  int get itemCount {
    if (needBuyVideo(videoModel)) {
      return min(6, videoModel?.seriesCover?.length ?? 0);
    }
    return videoModel?.seriesCover?.length ?? 0;
  }

  int get maxCount {
    int len = videoModel?.seriesCover?.length ?? 0;
    if (len > 6) len = 6;
    return len;
  }

  @override
  void initState() {
    super.initState();
    _indexNotifier.value = widget.index;
    if (widget.isFromDetail) {
      videoModel = widget.videoModel;
      Future.delayed(Duration(milliseconds: 250), () {
        itemScrollCtr.scrollTo(index: widget.index, duration: Duration(milliseconds: 100));
      });
    } else {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _loadData();
      });
    }
  }

  void _loadData() async {
    videoModel = await VidService.getVideoDetail(widget.videoModel?.id ?? "");
    _sendRecord();
    // if (needBuyVideo(videoModel)) {
    //   _showBuyEvent(context);
    // }

    if (videoModel == null) {
      videoModel ??= VideoModel();
    }
    if (mounted) setState(() {});
    Future.delayed(Duration(milliseconds: 250), () {
      itemScrollCtr.scrollTo(index: widget.index, duration: Duration(milliseconds: 200));
    });
  }

  void _sendRecord() async {
    String videoID = videoModel?.id ?? "";
    int playWay = videoModel?.originCoins == 0 ? 0 : 1;
    int via = 1;
    String? tagID;
    if (videoModel?.tags?.isNotEmpty == true) {
      tagID = videoModel!.tags![0].id ?? "";
    }
    await VidService.sendVideoRecord(videoID, playWay: playWay, via: via, tagID: tagID);
  }

  bool isShowBuyAlert(int index) {
    if (needBuyVideo(videoModel) && (index == 5)) {
      return true;
    }
    return false;
  }

  void _showBuyEvent(BuildContext context) async {
    var ret = await Get.bottomSheet(VideoBuyBottomSheet(videoM: videoModel!));
    if (ret == true) {
      videoModel?.vidStatus?.hasPaid = true;
      widget.videoModel?.vidStatus?.hasPaid = true;
    }
    if (ret == false) {
      Get.back();
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('图片预览')),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {
    if (videoModel == null) {
      return LoadingCenterWidget();
    } else if (videoModel?.seriesCover?.isNotEmpty != true) {
      return CErrorWidget(
        retryOnTap: () {
          videoModel = null;
          setState(() {});
          _loadData();
        },
      );
    }
    return Column(
      children: [
        Expanded(
          child: ScrollablePositionedList.builder(
              itemPositionsListener: itemPositionsListener,
              itemCount: itemCount,
              itemScrollController: itemScrollCtr,
              itemBuilder: (context, index) {
                String imageUrl = videoModel!.seriesCover![index];
                return GestureDetector(
                  onTap: () async {
                    Get.to(ImageScaleView(url: imageUrl, isPage: true));
                  },
                  child: NetworkImageLoader(
                    imageUrl: imageUrl,
                    borderRadius: 0,
                    compress: true,
                  ),
                );
              }),
        ),
        ValueListenableBuilder<Iterable<ItemPosition>>(
          valueListenable: itemPositionsListener.itemPositions,
          builder: (context, value, child) {
            return AlbumActionWidget(
              videoModel: videoModel,
              currentIndex: value.length > 0 ? value.first.index : 1,
            );
          },
        )
      ],
    );
  }
}
